<?php
   
    include '/public/sql_pdo_lib.php';
    header('Content-type: application/json');
    ini_set('display_errors','ON');
    error_reporting(E_ALL);
    // ini_set('max_execution_time', 10);
    

    $db = new \PDO('sqlite:'.dirname(__FILE__).'/db/test.db'); 

    $post_str = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
    $postData = json_decode($post_str,true);


    // 19.01.16

    $action = $postData['action'];

    if($action=='take_search'){
        # code...
        take_search($postData,$db);
    }else if($action=='search'){
        # code...
        action_search($postData,$db);
    }else if($action=='add'){
        # code...
        action_add($postData,$db);
    }else if($action=='del'){
        # code...
        action_del($postData,$db);
    }else if($action=='insert') {
        # code...
        action_insert($postData,$db);
    }else if ($action=='upData') {
        # code...
        action_upData($postData,$db);
    }elseif ($action=='visit_site') {
        # code...
        visit_site($postData,$db);
    }elseif ($action=='take_describe') {
        # code...
        take_describe($postData,$db);
    }elseif ($action=='take_works') {
        # code...
        take_works($postData,$db);
    }elseif ($action=='take_image') {
        # code...
        take_image($postData,$db);
    }elseif ($action=='take_works_content') {
        # code...
        take_works_content($postData,$db);
    }

    function take_works_content($postData,$db_name)
    {
        # code...
        
        // 获取链接
        $query_url = 'http://www.nanrenvip8.net'.$postData['data']['works_content_url'];
        // $query_url = 'http://www.nanrenvip8.net'.'/jingxiangjulia/2015/MIDE-235.html';
        // 访问网址
        $result =postPage($query_url);
        // 去格式
        $result = DeleteHtml($result);
        // 正则
        $reg_works_content = '/(artCon).*?\<\/[p]+\>/';
        // 匹配正则
        preg_match ($reg_works_content, $result, $works_content);

        if ($works_content == null) {
            # code...
            $word = '"",'."\r\n";
        } else {
            # code...
            $works_content_url = explode('>', $works_content[0]);
            $works_content_url = array_slice($works_content_url,-2,1);
            $works_content_url = preg_replace("/\<\/[p]+/","",$works_content_url[0]);
            $word = '"'.$works_content_url.'",'."\r\n";
        }

        $filename = 'works_content.txt';

        $fh = fopen($filename, "a");
        fwrite($fh, $word);


        $id = $postData['data']["id"];

        $record = array("image_download"=> '3');
        $where_sql = "where id = :id";
        $bind_var=array("id"=>$id);

        $new=pdo_fn_bool_update($db_name, "works_code", $record, $where_sql, $bind_var);        

    }



    function take_image($postData,$db_name)
    {
        # code...

        $image_url = $postData['data']['works_image'];
        $file_name = $postData['data']['actress_id'];

        // 图片名字
        $pic_name = substr(strrchr($image_url,'/'),1);
        // 文件名称
        $file_name = preg_replace("/\-/","",$file_name);


        function geturldata($url,$out_time="10000") 
        { 
            $ch = curl_init(); 
            curl_setopt ($ch, CURLOPT_URL, $url); 
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
            curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 1); 
            curl_setopt($ch, CURLOPT_PROXY, 'http://127.0.0.1:1080'); 
            curl_setopt ($ch, CURLOPT_TIMEOUT_MS, $out_time);
            $content = curl_exec($ch); 
            return $content; 
        } 
        $pic_content = geturldata($image_url);

        //创建可抛出一个异常的函数
        function checkYes($return){
            if($return==""){
                throw new Exception("运行 catch ");
            }
            return true;
        }

        //在 "try" 代码块中触发异常
        try{
            checkYes($pic_content);

            $location_url = realpath('allImage');
            $dir = iconv("UTF-8", "GBK", "allImage/".$file_name);
            if (!file_exists($dir)){
                mkdir ($dir,0777,true);
                file_put_contents($location_url.'/'.$file_name.'/'.$pic_name, $pic_content);
            }else{
                file_put_contents($location_url.'/'.$file_name.'/'.$pic_name, $pic_content);
            }
            $id = $postData['data']["id"];

            $record = array("image_download"=> '2');
            $where_sql = "where id = :id";
            $bind_var=array("id"=>$id);

            $new=pdo_fn_bool_update($db_name, "works_code", $record, $where_sql, $bind_var);
        }    
        //捕获异常
        catch(Exception $e){
            $pic_content = geturldata($image_url);
            
            $location_url = realpath('allImage');
            $dir = iconv("UTF-8", "GBK", "allImage/".$file_name);
            if (!file_exists($dir)){
                mkdir ($dir,0777,true);
                file_put_contents($location_url.'/'.$file_name.'/'.$pic_name, $pic_content);
            }else{
                file_put_contents($location_url.'/'.$file_name.'/'.$pic_name, $pic_content);
            }
            $id = $postData['data']["id"];

            $record = array("image_download"=> '2');
            $where_sql = "where id = :id";
            $bind_var=array("id"=>$id);

            $new=pdo_fn_bool_update($db_name, "works_code", $record, $where_sql, $bind_var);        
        }

    }


    function take_works($postData,$db_name)
    {
        # code...
        // 获取链接
        $query_url = 'http://www.nanrenvip8.net/'.$postData['data']['works_url'].'/';
        // 访问网址
        $result =postPage($query_url);
        // 去格式
        $result = DeleteHtml($result);
        // 转字符串
        $result = $result;
        // print_r($result);
        // 作品日期 正则
        $reg_works_date = '/\d{4}\-\d+\-\d+/';
        // 匹配正则
        preg_match_all ($reg_works_date, $result, $works_date);
        $works_date_arr = $works_date[0];

        // 作品名称 正则
        $reg_works_name = '/\<[strong]{6}\>.*?\</';
        // 匹配正则
        $works_name_arr = [];
        preg_match_all ($reg_works_name, $result, $works_name);
        // 总数
        $works_num = end($works_name[0]);
        preg_match ('/\d+/', $works_num, $works_num);
        $works_num = $works_num[0];

        array_pop($works_name[0]);
        array_pop($works_name[0]);

        foreach ($works_name[0] as $key => $value) {
            # code...
            $works_content_url = explode('>', $value)[1];
            $works_content_url = explode('<', $works_content_url)[0];
            array_push($works_name_arr, $works_content_url);
        }
        // echo '名称统计：'.count($works_name_arr).'<br>';
        // print_r($works_name_arr);



        // 作品番号 正则
        $reg_works_code = '/\<[b]+\>.*?\<\/[b]+\>/';
        // 匹配正则
        $works_content_url_arr = [];
        $works_code_arr = [];
        preg_match_all ($reg_works_code, $result, $works_code_content);
        foreach ($works_code_content[0] as $key => $value) {
            # code...
            $works_url = explode('=', $value)[1];
            // 获取作品详情链接
            $works_content_url = explode('>', $works_url)[0];
            array_push($works_content_url_arr,$works_content_url);

            // 获取作品番号
            $works_code = explode('/', $works_content_url);
            $works_code = end($works_code);
            $works_code = explode('.', $works_code)[0];
            array_push($works_code_arr,$works_code);
        }
        // echo '番号统计：'.count($works_code_arr).'<br>';
        // echo '详情链接统计：'.count($works_content_url_arr).'<br>';
        // print_r($works_code_arr);
        // print_r($works_content_url_arr);


        // 作品图片 正则
        $reg_works_image = '/(?=o)[original]{8}.*?\/\>/';
        // 匹配
        preg_match_all ($reg_works_image, $result, $works_image);
        $works_image_arr = preg_replace("/\/\>/","",$works_image[0]); 
        $works_image_arr = preg_replace("/\w*\=/","",$works_image_arr); 
        // echo '图片统计：'.count($works_image_arr).'<br>';
        // print_r($works_image_arr);

        // 数据入库

        $actress_id = $postData['data']["id"];

        foreach ($works_name_arr as $key => $value) {
            # code...
            $works_name = $value;
            if (!isset($key)) {
                # code...
                print_r("尚未赋值");
            } else {
                # code...
                @$works_date = $works_date_arr[$key];
                @$works_content_url = $works_content_url_arr[$key];
                @$works_code = $works_code_arr[$key];
                @$works_image = $works_image_arr[$key];

                $table=array("works_code"=>array(array("actress_id"=>$actress_id,'works_code'=>$works_code,'works_image'=>$works_image,'works_name'=>$works_name,'works_date'=>$works_date,'works_content_url'=>$works_content_url)));
                $call_result=pdo_fn_bool_insert($db_name, $table);
            }
            
        }

        $date_count = count($works_date_arr);

        $record = array("take_works"=> '1',"works_num"=> $works_num,"take_works_num"=> $date_count);
        $where_sql = "where id = :id";
        $bind_var=array("id"=>$actress_id,"works_num"=>$works_num,"take_works_num"=> $date_count);


        $new=pdo_fn_bool_update($db_name, "actress", $record, $where_sql, $bind_var);

    }

    function action_search($postData,$db_name){
        
        $actress_name = $postData["actress_name"];
        $pageid = $postData["pageid"];
        $bind_var=array("actress_name"=>"%".$actress_name."%" , "pageid"=>($pageid-1)*10);

        $sql=pdo_fn_str_create_string(function(){/*
            SELECT id,actress_name,hot,actress_images FROM actress WHERE actress_name LIKE :actress_name LIMIT 10 OFFSET :pageid;
        */});
        $total = 'SELECT count(id) total FROM actress WHERE actress_name LIKE :actress_name';
        $result=pdo_fn_array_select($db_name, $sql, $bind_var);
        $total=pdo_fn_array_select($db_name, $total, $bind_var)[0];
        $rowcount = ceil($total['total']/10);
        $pageid = $pageid;
        $arrList = ['pagers'=>$total['total'] , 'result'=>$result , 'pageid'=>$pageid, 'rowcount'=>$rowcount];
        
        echo json_encode($arrList);
    }

    function action_add($postData){

    }

    function action_del(){
        
    }

    function action_insert(){
        
    }

    function take_describe($postData,$db_name)
    {
        # code...
        if(!$postData['data']['works_url']){
            die($postData['data']['id'].'的url为空');
        }else {
            # code...
            $query_url = 'http://www.nanrenvip8.net/'.$postData['data']['works_url'].'/';

            # code...
            $actress_name = $postData['data']['actress_name'];
            // 访问网址
            $result =postPage($query_url);
            // 去格式
            $result = DeleteHtml($result);
            // 转字符串
            $result = $result;
            // 描述 正则
            $reg_describe = '/\<[pclass=avms]{11,}\>.*?\<[p]+\>/';
            // 匹配
            preg_match ($reg_describe, $result, $actress_describe_arr);
            // 判断是否为空
            if (!$actress_describe_arr) {
                # code...
                $actress_describe = '';
            } else {
                # code...
                $result_explode = explode('>', $actress_describe_arr[0])[1];
                $actress_describe = explode('<', $result_explode)[0];
            }

            // 入库
            $record = array("actress_describe"=>$actress_describe, "actress_describe_state"=>1);
            $where_sql = "where actress_name=:actress_name";
            $bind_var=array("actress_name"=>$actress_name, "actress_describe"=>$actress_describe);

            $new=pdo_fn_bool_update($db_name, "actress", $record, $where_sql, $bind_var);
            

            // 作品图片 正则

        }
    }

    function action_upData($postData){
        $actress_images_str = explode('/', $value['actress_images']);
        $actress_images = end($actress_images_str);
        $actress_name = $value['actress_name'];

        if ($actress_images == "pic.onemai.com" ) {
            # code...
            $actress_images = '';
        }

        $record = array("actress_images"=>$actress_images);
        $where_sql = "where actress_name=:actress_name";
        $bind_var=array("actress_name"=>$actress_name, "actress_images"=>$actress_images);

        $new=pdo_fn_bool_update($db, "actress", $record, $where_sql, $bind_var);
    }

    function take_search($postData,$db_name){

        $table_name = $postData['table_name'];

        if ($table_name == 'actress' || $table_name == 'works_code') {
            # code...
            $sql=pdo_fn_str_create_string(function(){/*
                SELECT * FROM {0} WHERE image_download = 2;
            */},[$table_name]);
            $result=pdo_fn_array_select($db_name, $sql);
            echo json_encode($result);
        }else{
            # code...
            echo '请输入正确的表名';
        }

    }

    function visit_site($postData,$db_name)
    {
        # code...
        // echo file_get_contents("http://www.nanrenvip8.net/find.html");
        $site_url = $postData['site_url'];
        $result = postPage($site_url); 
        // print_r($result);

        // 演员名字
        $reg_name = '/(\w*)?\(?([\x{4e00}-\x{9fa5}]*)?\)?\<\/\w{5}\>/u';
        preg_match_all ($reg_name, $result, $actress_name_arr);
        $actress_name_arr = array_splice($actress_name_arr[0],1); 
        $actress_name_arr_new = [];
        foreach ($actress_name_arr as $key => $value) {
            # code...
            $actress_name_arr_one = explode('<', $value)[0];
            array_push($actress_name_arr_new,$actress_name_arr_one);
        }

        // 演员路径
        $regex = '/\/\w*\/?"><img/';
        preg_match_all ($regex, $result, $matches);
        // 处理 reg 回来的 arr 到 actress_data_url
        $actress_data_url = [];
        $matches = $matches[0];
        foreach ($matches as $key => $value) {
            # code...
            $arr_one = explode('"', $value)[0];
            // 清除 左右的 " / "
            $arr_one = ltrim(rtrim($arr_one, "/"),"/");
            array_push($actress_data_url, $arr_one);
        }

        foreach ($actress_data_url as $key => $value) {
            # code...

            $actress_name = $actress_name_arr_new[$key];
            $works_url = $value;

            $record = array("works_url"=>$works_url);
            $where_sql = "where actress_name=:actress_name";
            $bind_var=array("actress_name"=>$actress_name, "works_url"=>$works_url);

            $new=pdo_fn_bool_update($db_name, "actress", $record, $where_sql, $bind_var);
            print_r('入库了');
        }
    }

    function edit_images_url($postData)
    {
        # code...

        $sql=pdo_fn_str_create_string(function(){/*
            SELECT * FROM actress;
        */});
        $result=pdo_fn_array_select($db, $sql);

        foreach ($result as $key => $value) {
            # code...
            $actress_images_str = explode('/', $value['actress_images']);
            $actress_images = end($actress_images_str);
            $actress_name = $value['actress_name'];

            if ($actress_images == "pic.onemai.com" ) {
                # code...
                $actress_images = '';
            }

            $record = array("actress_images"=>$actress_images);
            $where_sql = "where actress_name=:actress_name";
            $bind_var=array("actress_name"=>$actress_name, "actress_images"=>$actress_images);

            $new=pdo_fn_bool_update($db, "actress", $record, $where_sql, $bind_var);
        }
    }


    
    // 访问网址
    function postPage($url) { 
        $response = ""; 
        $proxy='http://127.0.0.1:1080'; 
        if($url != "") { 
            $ch = curl_init($url); 
            curl_setopt($ch, CURLOPT_HEADER, 0); 
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
            curl_setopt($ch, CURLOPT_PROXY, $proxy); 
            $response = curl_exec($ch); 
            if(curl_errno($ch)){
                $response = ""; 
            }
            curl_close($ch); 
        } 
        return $response; 
    }

    // 演员简介
    function actress_about($two_level_url)
    {
        $result = postPage($two_level_url);
        # code...
        $reg_name = '/\<[p]\s\w+\=\'\w+\'\>.*\<\/[p]\>/';

        preg_match_all ($reg_name, $result, $actress_about);
        $actress_about = array_splice($actress_about[0],1); 
        $actress_about_new = [];
        foreach ($actress_name_arr as $key => $value) {
            # code...
            $actress_name_arr_one = explode('<', $value)[0];
            array_push($actress_name_arr_new,$actress_name_arr_one);
        }

    }

    // 清除html 空格和换行
    function DeleteHtml($str) 
    { 
        $str = trim($str); //清除字符串两边的空格
        $str = preg_replace("/\t/","",$str); //使用正则表达式替换内容，如：空格，换行，并将替换为空。
        $str = preg_replace("/\"/","",$str); //使用正则表达式替换内容，如："，并将替换为'。
        $str = preg_replace("/\'/","",$str); 
        $str = preg_replace("/\r\n/","",$str); 
        $str = preg_replace("/\r/","",$str); 
        $str = preg_replace("/\n/","",$str); 
        // $str = preg_replace("/ /","",$str);
        $str = preg_replace("/  /","",$str);  //匹配html中的空格
        return trim($str); //返回字符串
    }

    // 挑选



    // 19.01.16

    // $arr = json_decode($post_str,true);
    // // $pageid = $pageid;


    // $arrList = ['pagers'=>$total['total'] , 'result'=>$result , 'pageid'=>$pageid, 'rowcount'=>$rowcount];

    // echo json_encode($arrList);




    //     // $sql = 'SELECT * FROM actress WHERE actress_name LIKE :actress_name';
    //     // $pages = 'SELECT * FROM actress ORDER BY hot DESC LIMIT 10 OFFSET 0';
        
    // }

    // selectData($post_str,$db);

    $db = null;
?>

